package com.cn.hotel.util;

import com.mysql.cj.protocol.Resultset;

import java.sql.*;


public class JDBC {
    private static final String URL = "jdbc:mysql://localhost:3306/businesshotel?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
    private static final String USER = "root";
    private static final String PASSWORD = "root";


    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");//加载数据库驱动 反射机制
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /*
     * 连接数据库需要几个特殊的类：
     * 1、Connection  得到连接
     * 2、PreparedStatement
     * 3、ResultSet
     * */
    private static PreparedStatement prepareStatement = null;
//    private static Connection connection = null;
    private static ResultSet resultSet = null;

    private JDBC() {
    }

    //连接数据库到指定数据库，并判断是否成功
    public static Connection getConn() {
        Connection connection = null;
        try {
            if (connection == null) {
                connection = DriverManager.getConnection(URL, USER, PASSWORD);//建立连接
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
//            close();
        }
        return connection;
    }

    /*
     *增加 修改 删除
     * */
    public static int executeUpdate(String sql) {
        Connection connection = getConn();
        int count = 0;
        try {
            prepareStatement = connection.prepareStatement(sql);
            count = prepareStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close();
        }
        return count;
    }
    //查询数据库
    public static ResultSet getResultSet(String sql){
        Connection connection = getConn();
        try {
            prepareStatement = connection.prepareStatement(sql);
            resultSet = prepareStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }
    public static void close() {
//        if (connection != null) {
//            try {
//                connection.close();
//                connection = null;
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
        if (prepareStatement != null) {
            try {
                prepareStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            prepareStatement = null;
        }
    }

}
